package com.haixiaoke.saas.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.haixiaoke.saas.common.core.redis.RedisCache;
import com.haixiaoke.saas.system.domain.SysNotice;
import com.haixiaoke.saas.system.mapper.SysNoticeMapper;
import com.haixiaoke.saas.system.service.ISysNoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 公告 服务层实现
 *
 * @author haixiaoke
 */
@Service
public class SysNoticeServiceImpl implements ISysNoticeService {

    public static final String NOTICE_HIGHLIGHT_TIME = "notice_highlight_time";

    @Autowired
    private SysNoticeMapper noticeMapper;

    @Autowired
    private RedisCache redisCache;
    /**
     * 查询公告信息
     *
     * @param noticeId 公告ID
     * @return 公告信息
     */
    @Override
    public SysNotice selectNoticeById(Long noticeId) {
        return noticeMapper.selectNoticeById(noticeId);
    }

    /**
     * 查询公告列表
     *
     * @param notice 公告信息
     * @return 公告集合
     */
    @Override
    public List<SysNotice> selectNoticeList(SysNotice notice) {
        return noticeMapper.selectNoticeList(notice);
    }

    /**
     * 新增公告
     *
     * @param notice 公告信息
     * @return 结果
     */
    @Override
    public int insertNotice(SysNotice notice) {
        setHighlightTime(notice);
        return noticeMapper.insertNotice(notice);
    }

    private void setHighlightTime(SysNotice notice) {
        Integer highlightTime = notice.getHighlightTime();
        if (highlightTime != null && highlightTime > 0){
            long noticeHighlightTime = redisCache.getExpire(NOTICE_HIGHLIGHT_TIME);
            if (noticeHighlightTime > 0){
                long expirationTime = highlightTime*24*60*60L;
                if (expirationTime > noticeHighlightTime){
                    redisCache.expire(NOTICE_HIGHLIGHT_TIME,expirationTime,TimeUnit.SECONDS);
                }
            }else{
                redisCache.setCacheObject(NOTICE_HIGHLIGHT_TIME,notice.getNoticeId(),highlightTime*24*60, TimeUnit.MINUTES);
            }
        }
    }

    /**
     * 修改公告
     *
     * @param notice 公告信息
     * @return 结果
     */
    @Override
    public int updateNotice(SysNotice notice) {
        setHighlightTime(notice);
        return noticeMapper.updateNotice(notice);
    }

    /**
     * 删除公告对象
     *
     * @param noticeId 公告ID
     * @return 结果
     */
    @Override
    public int deleteNoticeById(Long noticeId) {
        return noticeMapper.deleteNoticeById(noticeId);
    }

    /**
     * 批量删除公告信息
     *
     * @param noticeIds 需要删除的公告ID
     * @return 结果
     */
    @Override
    public int deleteNoticeByIds(Long[] noticeIds) {
        return noticeMapper.deleteNoticeByIds(noticeIds);
    }
}
